package com.controller;

import com.bean.Enterprise;
import com.bean.Page;
import com.bean.User;
import com.google.gson.Gson;
import com.service.EnterpriseService;
import com.service.impl.EnterpriseServiceImpl;
import com.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class EnterpriseServlet extends BaseServlet {

    private EnterpriseService enterpriseService=new EnterpriseServiceImpl();

    /**
     * 判断用户编号是否存在
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void ajaxExistsEnterpriseid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String enterpriseid=req.getParameter("enterpriseid");
        boolean existsEnterpriseid=enterpriseService.existsEnterpriseid(enterpriseid);
        //封装成Map对象
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("existsEnterpriseid",existsEnterpriseid);
        Gson gson=new Gson();
        String json=gson.toJson(resultMap);
        resp.getWriter().write(json);
    }

    /**企业用户登录
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取请求的参数
        String enterpriseid=req.getParameter("enterpriseid");
        String password=req.getParameter("password");
        String code=req.getParameter("code");

        //获取验证码
        String token=(String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        //判断验证码
        if( token!=null && token.equalsIgnoreCase(code)){
            //调用userService.login()登录
            Enterprise loginEnterprise=enterpriseService.login(new Enterprise(enterpriseid,password));
            //根据Login（）方法返回结果判断登录是否成功
            if(loginEnterprise==null){
                //返回登录页面
                req.setAttribute("mess","请重新输入企业用户id和密码！");
                req.getRequestDispatcher("/page/loginEnterprise/login.jsp").forward(req,resp);
            }else{
                //登录成功
                //保存信息至session
                req.getSession().setAttribute("enterprise",loginEnterprise);
                req.getRequestDispatcher("/page/enterprise/indexEnterprise.jsp").forward(req,resp);
            }
        }else{
            System.out.print(code+"验证码错误");
            req.setAttribute("mess",code+"验证码错误");
            req.getRequestDispatcher("/page/loginEnterprise/login.jsp").forward(req,resp);
        }
    }

    /**
     * 企业用户注册
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取请求参数
        String again_password=req.getParameter("again_password");
        String code=req.getParameter("code");
        Enterprise enterprise=WebUtils.copyParamToBean(req.getParameterMap(),new Enterprise());
        //获取验证码
        String token=(String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        WebUtils.copyParamToBean(req.getParameterMap(),enterprise);

        //验证码是否正确
        if( token!=null && token.equalsIgnoreCase(code)){
            //正确
            // 判断两次密码是否相同
            if(again_password.equals(enterprise.getPassword())){
                //判断用户id是否可用
                if(enterpriseService.existsEnterpriseid(enterprise.getEnterpriseid())){
                    //已存在，不可用
                    // System.out.print(userid+"已存在，不可用");
                    req.setAttribute("mess","企业用户名已存在！");
                    req.getRequestDispatcher("/page/loginEnterprise/register.jsp").forward(req,resp);
                }else{
                    //调用servlet保存到数据库
                    enterpriseService.register(enterprise);
                    req.getSession().setAttribute("enterprise",enterprise);
                    req.getRequestDispatcher("/page/enterprise/indexEnterprise.jsp").forward(req,resp);
                }
            }else{
                System.out.print("两次输入的密码不相同");
                req.setAttribute("mess","两次输入的密码不相同！");
                req.getRequestDispatcher("/page/loginEnterprise/register.jsp").forward(req,resp);
            }
        }else{
            //不正确
            System.out.print("验证码"+code+"不正确");
            req.setAttribute("mess","验证码"+code+"不正确");
            req.getRequestDispatcher("/page/loginEnterprise/register.jsp").forward(req,resp);
        }
    }

    /**
     * 修改密码
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void modifyPass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String password=req.getParameter("password");
        String again_password=req.getParameter("again_password");
        Enterprise enterprise= (Enterprise) req.getSession().getAttribute("enterprise");
        String enterpriseid=enterprise.getEnterpriseid();
        if(again_password.equals(password)){
            try {
                enterpriseService.updatePass(enterpriseid,password);
                System.out.println("密码修改成功");
                req.getRequestDispatcher("/page/enterprise/modifyPass.jsp").forward(req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }else {
            System.out.println("密码修改失败");
            req.setAttribute("mess","密码修改失败");
            req.getRequestDispatcher("/page/enterprise/modifyPass.jsp").forward(req,resp);

        }
    }


    /**
     *编辑基本信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void modifyMess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Enterprise enterprise= (Enterprise) req.getSession().getAttribute("enterprise");
        String enterpriseid=enterprise.getEnterpriseid();
        String enterprise_name=req.getParameter("enterprise_name");
        String relname=req.getParameter("relname");
        String telephone=req.getParameter("telephone");
        String address=req.getParameter("address");
        enterpriseService.updateMess(enterpriseid,enterprise_name,relname,telephone,address);

        enterprise.setEnterprise_name(enterprise_name);
        enterprise.setRelname(relname);
        enterprise.setTelephone(telephone);
        enterprise.setAddress(address);
        req.getSession().setAttribute("enterprise",enterprise);
        req.getRequestDispatcher("/page/enterprise/showMess.jsp").forward(req,resp);

    }


    /**
     * 退出登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //
        req.getSession().invalidate();
        //
        resp.sendRedirect(req.getContextPath());
    }

    /**
     * 注销
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Enterprise enterprise= (Enterprise) req.getSession().getAttribute("enterprise");
        String enterpriseid=enterprise.getEnterpriseid();
        enterpriseService.delete(enterpriseid);
        resp.sendRedirect(req.getContextPath()+"/index.jsp");
    }

    /**
     *管理员查看企业用户
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void queryPageEnterprise(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int pageNo= WebUtils.parseInt(req.getParameter("pageNo"),1);
        int pageSize=WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        Page<Enterprise> page=enterpriseService.queryPageEnterprise(pageNo,pageSize);
        page.setUrl("enterpriseServlet?action=queryPageEnterprise");
        req.setAttribute("page",page);
        req.getRequestDispatcher("/page/admin/showAllEnterprise.jsp").forward(req,resp);
    }
}
